/*
 * Copyright (c) 2011 Imre Fazekas.
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * Neither the name of the Brillien nor the names of its
 * terms and concepts may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package com.vii.brillien.core.component.db;

import com.vii.brillien.core.component.SuperPresence;
import com.vii.brillien.core.management.db.TransactionServices;
import com.vii.brillien.kernel.BrillienException;
import com.vii.brillien.kernel.annotations.PresenceService;
import com.vii.brillien.kernel.annotations.lifecycle.Resident;
import com.vii.streamline.services.db.DBMediator;
import com.vii.streamline.services.error.StreamLineException;

import javax.transaction.Transaction;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Presence type to realize a Datasource for a DB.
 */
@PresenceService( logLevel = PresenceService.CONFIG)
@Resident
public class DataSource extends SuperPresence implements DBMediator {

    public String                               vendor;
    public String                               username;
    public String                               password;

    public String                               address;
    public String                               port;
    public String                               database;

    public boolean                              xaCapable;

    protected javax.sql.DataSource              ds;

    protected ConcurrentLinkedQueue<Connection> connections;

    @Override
    public void reset() {
        super.reset();

        address     = "localhost";
        username    = "";
        password    = "";

        connections = new ConcurrentLinkedQueue<Connection>();
    }

    /**
     * Getter method for the name of the Vendor of the DB solution
     */
    @Override
    public String  getVendor(){
        return vendor;
    }

    @Override
    public void setVendor(String vendor) {
        this.vendor = vendor;
    }


    /**
     * Getter method for the username
     */
    @Override
    public String  getUsername(){
        return username;
    }

    @Override
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * Getter method for the password
     */
    @Override
    public String  getPassword(){
        return password;
    }

    @Override
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * Getter method for the address of the DB
     */
    @Override
    public String getAddress(){
        return address;
    }

    @Override
    public void setAddress(String address) {
        this.address = address;
    }

    /**
     * Getter method for the port of the DB
     */
    @Override
    public String getPort(){
        return port;
    }

    @Override
    public void setPort(String port) {
        this.port = port;
    }

    /**
     * Getter method for the targeted schema name of the DB
     */
    @Override
    public String getDatabase(){
        return database;
    }

    @Override
    public void setDatabase(String database) {
        this.database = database;
    }

    @Override
    public boolean isXaCapable() {
        return xaCapable;
    }

    @Override
    public void setXaCapable(boolean xaCapable) {
        this.xaCapable = xaCapable;
    }


    /**
     * Gets the {@link javax.sql.DataSource}.
     */
    @Override
    public javax.sql.DataSource getDs() {
        return ds;
    }

    /**
     * Sets the {@link javax.sql.DataSource}.
     */
    @Override
    public void setDs(javax.sql.DataSource ds) {
        this.ds = ds;
    }

    @Override
    public <T extends Transaction> T startTransaction() throws StreamLineException {
        throw new StreamLineException("Cannot used this method in managed environment.");
    }

    @Override
    public <T extends Transaction> void closeTransaction(T t) throws StreamLineException, StreamLineException {
        throw new StreamLineException("Cannot used this method in managed environment.");
    }


    /**
     * Requests a new Connection
     */
    public Connection getConnection( boolean autocommit, int isolation ) throws BrillienException {
        try {
            Connection c = getConnection();
            c.setAutoCommit( autocommit );
            c.setTransactionIsolation( isolation );
            return c;
        } catch (SQLException e) {
            throw new BrillienException( e );
        }
    }

    /**
     * Requests a new Connection
     */
    public Connection getConnection() throws BrillienException {
        try {
            if( ds == null )
                throw new BrillienException( "DataSource instance is null!" );

            log( "Getting a connection... " );

            Connection c = ds.getConnection();
            connections.add( c );
            return c;
        } catch (SQLException e) {
            throw new BrillienException( e );
        }
    }

    /**
     * Retrieves a previously requests connection
     */
    public void retrieveConnection( Connection c ) throws BrillienException {
        try {
            log( "Retrieving connection ... " );
            c.close();
            connections.remove( c );
        } catch (SQLException e) {
            throw new BrillienException( e );
        }
    }

    @Override
    public void passivateAll() throws BrillienException {
        super.passivateAll();
        for (Connection connection : connections) {
            try {
                connection.close();
            } catch (SQLException e) { exceptionLog( DataSource.class.getName(), "passivateAll", e ); }
        }
        connections.clear();
        TransactionServices.unregisterConnectionFactory( this );
    }
    
}
